package com.ruoyi.web.controller.system;

import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.TimeHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购计划Controller
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Controller
@RequestMapping("/system/purchaseplan")
public class SysPurchaseplanController extends BaseController
{
    private String prefix = "system/purchaseplan";

    @Autowired
    private ISysPurchaseplanService sysPurchaseplanService;
    @Autowired
    private ISysOfferinfoService sysOfferinfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysPurchaseitemService sysPurchaseitemService;
    @Autowired
    private ISysBidinfoService sysBidinfoService;
    @Autowired
    private ISysGoodsService sysGoodsService;
    @RequiresPermissions("system:purchaseplan:view")
    @GetMapping("/purchaseplan1")
    public String purchaseplan1()
    {
        return prefix + "/purchaseplan";
    }
    @GetMapping("/purchaseplan2")
    public String purchaseplan2()
    {
        return prefix + "/purchaseplan2";
    }
    /**
     * 查询采购计划列表
     */
    @RequiresPermissions("system:purchaseplan:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysPurchaseplan sysPurchaseplan)
    {
        SysUser sysUser = ShiroUtils.getSysUser();

            sysPurchaseplan.setPurchasingUnitId(sysUser.getCompanyId());

        startPage();
        List<SysPurchaseplan> list = sysPurchaseplanService.selectSysPurchaseplanList(sysPurchaseplan);
        return getDataTable(list);
    }
/*    *//**
     * 查询采购计划列表
     *//*
    @RequiresPermissions("system:purchaseplan:list2")
    @PostMapping("/list2")
    @ResponseBody
    public TableDataInfo list2(SysPurchaseplan sysPurchaseplan)
    {
        SysUser sysUser = ShiroUtils.getSysUser();

        sysPurchaseplan.setPurchasingUnitId(sysUser.getCompanyId());

        startPage();
        List<SysPurchaseplan> list = sysPurchaseplanService.selectSysPurchaseplanList(sysPurchaseplan);
        return getDataTable(list);
    }*/
    /**
     * 导出采购计划列表
     */
    @RequiresPermissions("system:purchaseplan:export")
    @Log(title = "采购计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysPurchaseplan sysPurchaseplan)
    {
        List<SysPurchaseplan> list = sysPurchaseplanService.selectSysPurchaseplanList(sysPurchaseplan);
        ExcelUtil<SysPurchaseplan> util = new ExcelUtil<SysPurchaseplan>(SysPurchaseplan.class);
        return util.exportExcel(list, "purchaseplan");
    }

    /**
     * 新增采购计划
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {

        Long unitId = ShiroUtils.getUserId();
        SysUser sysUser = userService.selectUserById(unitId);
        mmap.put("unitName",sysUser.getUserName());
        mmap.put("unitId",sysUser.getCompanyId());

        return prefix + "/add";
    }

    /**
     * 新增保存采购计划
     */
    @RequiresPermissions("system:purchaseplan:add")
    @Log(title = "采购计划", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysPurchaseplan sysPurchaseplan)
    {
        sysPurchaseplan.setAttribute2(sysPurchaseplan.getAttribute2());
        sysPurchaseplan.setAttribute3("0");//计划中，未完成
        return toAjax(sysPurchaseplanService.insertSysPurchaseplan(sysPurchaseplan));
    }

    /**
     * 修改采购计划
     */
    @GetMapping("/edit/{purchasePlanId}")
    public String edit(@PathVariable("purchasePlanId") Long purchasePlanId, ModelMap mmap)
    {
        SysPurchaseplan sysPurchaseplan = sysPurchaseplanService.selectSysPurchaseplanById(purchasePlanId);
        if(sysPurchaseplan.getAttribute3().equals("0")){
            mmap.put("sysPurchaseplan", sysPurchaseplan);
            return prefix + "/edit";
        }else{
            return "该计划已经使用，不允许修改！";
        }
      /*  SysPurchasingunit sysPurchasingunit = sysPurchasingunitService.selectSysPurchasingunitById(sysPurchaseplan.getPurchasingUnitId());

        mmap.put("unitName",sysPurchasingunit.getUnitName());
        mmap.put("unitId",sysPurchasingunit.getPurchasingUnitId());*/

    }

    /**
     * 修改保存采购计划
     */
    @RequiresPermissions("system:purchaseplan:edit")
    @Log(title = "采购计划", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysPurchaseplan sysPurchaseplan)
    {

        return toAjax(sysPurchaseplanService.updateSysPurchaseplan(sysPurchaseplan));
    }

    /**
     * 删除采购计划
     */
    @RequiresPermissions("system:purchaseplan:remove")
    @Log(title = "采购计划", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String [] planIds = ids.split(",");
        int jieguo =0 ;
        for (int i = 0;i<planIds.length;i++){
            SysPurchaseplan sysPurchaseplan = sysPurchaseplanService.selectSysPurchaseplanById(Long.parseLong(planIds[i]));
            SysPurchaseitem sysPurchaseitem = new SysPurchaseitem();
            sysPurchaseitem.setPurchasePlanId(sysPurchaseplan.getPurchasePlanId());
            List<SysPurchaseitem> sysPurchaseitemList = sysPurchaseitemService.selectSysPurchaseitemList(sysPurchaseitem);
            if (sysPurchaseitemList.size() > 0) {
                return  AjaxResult.error("该计划下面有商品，不允许删除！");
                 }else{
                jieguo = sysPurchaseplanService.deleteSysPurchaseplanById(Long.parseLong(planIds[i]));
            }
           /* if(!sysPurchaseplan.getAttribute3().equals("0")){
                return  AjaxResult.error("该计划已被使用，不允许删除！");
            }else{
                jieguo = sysPurchaseplanService.deleteSysPurchaseplanById(Long.parseLong(planIds[i]));
            }*/
        }
        return toAjax(jieguo);
    }

    /**
     * 添加采购计划商品
     * @param purchasePlanId
     * @param mmap
     * @return
     */
    @RequiresPermissions("system:purchaseplan:list")
    @GetMapping("/detail/{purchasePlanId}")
    public String detail(@PathVariable("purchasePlanId") Long purchasePlanId, ModelMap mmap)
    {
        mmap.put("purchasePlan", sysPurchaseplanService.selectSysPurchaseplanById(purchasePlanId));
        mmap.put("purchasePlans", sysPurchaseplanService.selectSysPurchaseplanList(null));
        return "system/purchaseitem/purchaseitem";
    }
    /**
     * 采购单位查看报价单列表
     * @param purchasePlanId
     * @param mmap
     * @return
     */
    @RequiresPermissions("system:purchaseplan:list")
    @GetMapping("/findBaoJia/{purchasePlanId}")
    public String findBaoJia(@PathVariable("purchasePlanId") Long purchasePlanId, ModelMap mmap)
    {
        mmap.put("purchasePlan", sysPurchaseplanService.selectSysPurchaseplanById(purchasePlanId));
        mmap.put("purchasePlans", sysPurchaseplanService.selectSysPurchaseplanList(null));
        SysPurchaseitem sysPurchaseitem = new SysPurchaseitem();
        sysPurchaseitem.setPurchasePlanId(purchasePlanId);
        List<SysPurchaseitem> purchaseitemList = sysPurchaseitemService.selectSysPurchaseitemList(sysPurchaseitem);
        boolean isSucc = false;
        for(int i = 0;i<purchaseitemList.size();i++){
            SysBidinfo bidInfo = sysBidinfoService.findPurchaseitemId(purchaseitemList.get(i).getPurchaseItemId());
            if(bidInfo!=null){

                if(bidInfo.getBidStatus().equals("1")){
                    boolean flag = false;
                    flag= TimeHelper.StringSwitchDateHHmmss(TimeHelper.getCurrentTime()).after(bidInfo.getEndTime());
                    if(flag){
                        SysOfferinfo sysOfferinfo = new SysOfferinfo();
                        sysOfferinfo.setBidInfoId(bidInfo.getBidInfoId());
                        List<SysOfferinfo> oList = sysOfferinfoService.selectSysOfferinfoList(sysOfferinfo);
                        if(bidInfo.getLowerestNumber()!=0){
                            if(oList.size()<1){
                                bidInfo.setBidStatus("-1");
                                bidInfo.setAttribute1("无供应商报价!");
                                sysBidinfoService.updateSysBidinfo(bidInfo);
                                purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                            }
                            if(oList.size()>0&&oList.size()<bidInfo.getLowerestNumber()){
                                bidInfo.setBidStatus("-1");
                                bidInfo.setAttribute1("报价供应商数小于限制个数!");

                                sysBidinfoService.updateSysBidinfo(bidInfo);
                                purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                            }
                            if(oList.size()>=bidInfo.getLowerestNumber()){
                                double[] qian = new double[oList.size()];
                                for(int a=0;a<oList.size();a++){
                                    qian[a]=oList.get(a).getOfferAmount();
                                }
                                double min=qian[0];
                                for(int d=1;d<qian.length;d++){
                                    if(qian[d]<min){
                                        min=qian[d];
                                    }
                                }
                                double minQian = min;
                                int flags =0;
                                for(int d=0;d<qian.length;d++){
                                    if(minQian==qian[d]){
                                        flags+=1;
                                    }
                                }
                                if(flags>=2){
                                    bidInfo.setBidStatus("-1");
                                    bidInfo.setAttribute1("有相同的最低价!");
                                    sysBidinfoService.updateSysBidinfo(bidInfo);
                                    purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                                }
                                if(flags==1){
                                    bidInfo.setBidStatus("0");
                                    bidInfo.setAttribute1("竞价成功!");
                                    sysBidinfoService.updateSysBidinfo(bidInfo);
                                    purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                                }
                            }
                        }else{
                            if(oList.size()<1){
                                bidInfo.setBidStatus("-1");
                                bidInfo.setAttribute1("无供应商报价!");
                                sysBidinfoService.updateSysBidinfo(bidInfo);
                                purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                            }else{
                                bidInfo.setBidStatus("0");
                                bidInfo.setAttribute1("竞价成功!");
                                sysBidinfoService.updateSysBidinfo(bidInfo);
                                purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
                            }
                        }
                    }
                }
            }
            if(bidInfo != null && bidInfo.getBidStatus().equals("0")){
                isSucc = true;
                purchaseitemList.get(i).setBidStatus(bidInfo.getBidStatus());
            }

            SysGoods sysGoods = sysGoodsService.selectSysGoodsById(purchaseitemList.get(i).getGoodsId());
            purchaseitemList.get(i).setSysGoods(sysGoods);
            purchaseitemList.get(i).setSysBidinfo(bidInfo);

        }
        mmap.put("lists", purchaseitemList);
        mmap.put("purchasePlanId", purchasePlanId);
        mmap.put("isSuccess", isSucc);
        return "system/purchaseitem/purchaseitem2";
    }

}
